package com.soft.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.soft.entity.Team;
import com.soft.entity.TeamDefaultPermission;
import com.soft.entity.TeamMember;
import com.soft.service.TeamService;

/**
 * 团队接口（/team）：
 * - 团队：创建/更新/删除/查询/列表（GET 与 POST 兼容创建）
 * - 成员：增删改查、REST风格别名与容错路径/memberrole 兼容
 * - 权限：增删改查、校验
 */
@RestController
@RequestMapping("/team")
public class TeamController {

    @Autowired
    private TeamService teamService;

    // 团队基本操作
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public Map<String, Object> createTeam(
            @RequestParam String teamName,
            @RequestParam String description,
            @RequestParam Integer creatorId) {
        Map<String, Object> result = new HashMap<>();
    // 1) 团队名唯一性校验，避免重复创建
        if (teamService.checkTeamNameExist(teamName)) {
            result.put("success", false);
            result.put("message", "团队名称已存在");
            return result;
        }

    // 2) 创建团队并返回完整实体（包含新teamId）
        Team team = teamService.createTeam(teamName, description, creatorId);
        result.put("success", true);
        result.put("data", team);
        return result;
    }

    // 支持POST方法创建团队（兼容前端JSON请求）
    public static class CreateTeamReq {
        public String teamName;
        public String description;
        public Integer creatorId;
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Map<String, Object> createTeamPost(@org.springframework.web.bind.annotation.RequestBody CreateTeamReq req) {
        Map<String, Object> result = new HashMap<>();
    // 1) 参数空值与必填检查
        if (req == null || req.teamName == null || req.teamName.trim().isEmpty()) {
            result.put("success", false);
            result.put("message", "团队名称不能为空");
            return result;
        }
        
        if (req.creatorId == null) {
            result.put("success", false);
            result.put("message", "创建者ID不能为空");
            return result;
        }
        
    // 2) 唯一性检查
        if (teamService.checkTeamNameExist(req.teamName)) {
            result.put("success", false);
            result.put("message", "团队名称已存在");
            return result;
        }

    // 3) 调用服务创建
        Team team = teamService.createTeam(req.teamName, req.description, req.creatorId);
        result.put("success", true);
        result.put("data", team);
        return result;
    }

    // 更新团队基础信息
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public Map<String, Object> updateTeam(
            @RequestParam Integer teamId,
            @RequestParam String teamName,
            @RequestParam String description) {
        Map<String, Object> result = new HashMap<>();
    // 1) 直接调用服务层更新，服务层可包含存在性/权限校验
        boolean success = teamService.updateTeam(teamId, teamName, description);
        result.put("success", success);
        if (!success) {
            result.put("message", "更新失败，团队可能不存在");
        }
        return result;
    }

    // 删除团队
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public Map<String, Object> deleteTeam(@RequestParam Integer teamId) {
        Map<String, Object> result = new HashMap<>();
    // 1) 删除团队（可能级联或软删除，具体由服务层控制）
        boolean success = teamService.deleteTeam(teamId);
        result.put("success", success);
        if (!success) {
            result.put("message", "删除失败，团队可能不存在");
        }
        return result;
    }

    // 按ID获取团队
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public Map<String, Object> getTeam(@RequestParam Integer teamId) {
        Map<String, Object> result = new HashMap<>();
    // 1) 按ID查询团队，返回 data 或错误信息
        Team team = teamService.getTeam(teamId);
        if (team != null) {
            result.put("success", true);
            result.put("data", team);
        } else {
            result.put("success", false);
            result.put("message", "团队不存在");
        }
        return result;
    }

    // 获取创建者的所有团队
    @RequestMapping(value = "/list/creator", method = RequestMethod.GET)
    public Map<String, Object> getTeamsByCreator(@RequestParam Integer creatorId) {
        Map<String, Object> result = new HashMap<>();
    // 1) 查询创建者创建的团队列表
        List<Team> teams = teamService.getTeamsByCreator(creatorId);
        result.put("success", true);
        result.put("data", teams);
        return result;
    }
    
    // 获取用户所在的所有团队
    @RequestMapping(value = "/list/user", method = RequestMethod.GET)
    public Map<String, Object> getTeamsByUserId(@RequestParam Integer userId) {
        Map<String, Object> result = new HashMap<>();
    // 1) 查询用户参与（成员或leader）的团队列表
        List<Team> teams = teamService.getTeamsByUserId(userId);
        result.put("success", true);
        result.put("data", teams);
        return result;
    }
    
    // 获取所有团队
    @RequestMapping(value = "/list/all", method = RequestMethod.GET)
    public Map<String, Object> getAllTeams() {
        Map<String, Object> result = new HashMap<>();
    // 1) 返回全量团队（可能用于管理端）
        List<Team> teams = teamService.getAllTeams();
        result.put("success", true);
        result.put("data", teams);
        return result;
    }

    // 团队成员管理
    @RequestMapping(value = "/member/add", method = RequestMethod.GET)
    public Map<String, Object> addMember(
            @RequestParam Integer teamId,
            @RequestParam Integer userId,
            @RequestParam String teamRole) {
        Map<String, Object> result = new HashMap<>();
    // 1) 新增成员，服务层可校验是否重复加入
        try {
            boolean success = teamService.addMember(teamId, userId, teamRole);
            result.put("success", success);
            if (!success) {
                result.put("message", "添加失败，成员可能已存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加成员时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    // 移除成员：默认从 Header X-User-Id 识别操作者
    @RequestMapping(value = "/member/remove", method = RequestMethod.GET)
    public Map<String, Object> removeMember(
            @RequestParam Integer teamId,
            @RequestParam Integer userId,
            jakarta.servlet.http.HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        Integer operatorId = null;
        if (request != null) {
            // 1) 优先从请求头读取操作人ID，便于服务层做权限判断
            String h = request.getHeader("X-User-Id");
            if (h != null && !h.isEmpty()) {
                try { operatorId = Integer.valueOf(h); } catch (Exception ignored) {}
            }
        }
        // 2) 移除成员，失败时返回提示
        boolean success = teamService.removeMember(teamId, userId, operatorId);
        result.put("success", success);
        if (!success) {
            result.put("message", "移除失败，权限不足或不允许移除");
        }
        return result;
    }

    // 更新成员角色：支持错误参数名容错与从 Header 取操作者ID
    @RequestMapping(value = "/member/role/update", method = RequestMethod.GET)
    public Map<String, Object> updateMemberRole(
            @RequestParam(value = "teamId", required = false) Integer teamId,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "teamRole", required = false) String teamRole,
            @RequestParam(value = "operatorId", required = false) Integer operatorId,
            // 容错：错误拼写参数
            @RequestParam(value = "teamld", required = false) Integer teamIdTypo,
            @RequestParam(value = "userld", required = false) Integer userIdTypo,
            @RequestParam(value = "operatorld", required = false) Integer operatorIdTypo,
            jakarta.servlet.http.HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
    // 1) 兼容错误参数名：优先使用正确参数，否则回退到容错参数
    Integer effTeamId = teamId != null ? teamId : teamIdTypo;
    Integer effUserId = userId != null ? userId : userIdTypo;
    Integer effOperatorId = operatorId != null ? operatorId : (operatorIdTypo != null ? operatorIdTypo : null);
        // 优先从 Header 获取操作者ID（更安全）
        if (effOperatorId == null && request != null) {
            String h = request.getHeader("X-User-Id");
            if (h != null && !h.isEmpty()) {
                try { effOperatorId = Integer.valueOf(h); } catch (Exception ignored) {}
            }
        }
    // 2) 最后兜底：仍为空则用被操作人ID（不安全，仅为兼容旧端）
        if (effOperatorId == null && effUserId != null) { effOperatorId = effUserId; }
    // 3) 执行业务并返回结果
    boolean success = teamService.updateMemberRole(effTeamId, effUserId, teamRole, effOperatorId);
        result.put("success", success);
        if (!success) {
            result.put("message", "更新失败，权限不足或成员不存在");
        }
        return result;
    }

    // 兼容：提供 POST JSON 方式，避免前端 GET 丢参导致的 400
    @RequestMapping(value = "/member/role/update", method = RequestMethod.POST)
    public Map<String, Object> updateMemberRolePost(
            @org.springframework.web.bind.annotation.RequestBody Map<String, Object> body,
            jakarta.servlet.http.HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 1) 参数存在性检查
            if (body == null) {
                result.put("success", false);
                result.put("message", "请求体为空");
                return result;
            }
            // 2) 解析参数，并尽量从 Header 获取 operatorId 提高安全性
            Integer teamId = body.get("teamId") == null ? null : Integer.valueOf(body.get("teamId").toString());
            Integer userId = body.get("userId") == null ? null : Integer.valueOf(body.get("userId").toString());
            Integer operatorId = body.get("operatorId") == null ? null : Integer.valueOf(body.get("operatorId").toString());
            if (operatorId == null && request != null) {
                String h = request.getHeader("X-User-Id");
                if (h != null && !h.isEmpty()) {
                    try { operatorId = Integer.valueOf(h); } catch (Exception ignored) {}
                }
            }
            String teamRole = body.get("teamRole") == null ? null : body.get("teamRole").toString();
            // 3) 执行业务更新角色
            boolean success = teamService.updateMemberRole(teamId, userId, teamRole, operatorId);
            result.put("success", success);
            if (!success) {
                result.put("message", "更新失败，权限不足或成员不存在");
            }
            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "请求参数错误: " + e.getMessage());
            return result;
        }
    }

    // 兼容/容错：历史/错误路径 "memberrole"（少了斜杠），以及错误参数名 teamld/userld
    @RequestMapping(value = "/memberrole/update", method = RequestMethod.GET)
    public Map<String, Object> updateMemberRoleAlias(
            @RequestParam(value = "teamId", required = false) Integer teamId,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "teamRole", required = false) String teamRole,
            @RequestParam(value = "operatorId", required = false) Integer operatorId,
            // 错误拼写兼容
            @RequestParam(value = "teamld", required = false) Integer teamIdTypo,
            @RequestParam(value = "userld", required = false) Integer userIdTypo,
            @RequestParam(value = "operatorld", required = false) Integer operatorIdTypo,
            jakarta.servlet.http.HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
    // 1) 兼容历史/错误路径与参数名
    Integer effTeamId = teamId != null ? teamId : teamIdTypo;
    Integer effUserId = userId != null ? userId : userIdTypo;
    Integer effOperatorId = operatorId != null ? operatorId : (operatorIdTypo != null ? operatorIdTypo : null);
        if (effOperatorId == null && request != null) {
            String h = request.getHeader("X-User-Id");
            if (h != null && !h.isEmpty()) {
                try { effOperatorId = Integer.valueOf(h); } catch (Exception ignored) {}
            }
        }
    // 2) 最后兜底保持与 GET 一致
    if (effOperatorId == null && effUserId != null) { effOperatorId = effUserId; }
    boolean success = teamService.updateMemberRole(effTeamId, effUserId, teamRole, effOperatorId);
        result.put("success", success);
        if (!success) {
            result.put("message", "更新失败，参数错误或权限不足");
        }
        return result;
    }

    // 兼容：POST JSON 的容错路径
    @RequestMapping(value = "/memberrole/update", method = RequestMethod.POST)
    public Map<String, Object> updateMemberRoleAliasPost(@org.springframework.web.bind.annotation.RequestBody Map<String, Object> body) {
        Map<String, Object> result = new HashMap<>();
    // 1) 参数检查
    if (body == null) { result.put("success", false); result.put("message", "请求体为空"); return result; }
        Integer teamId = body.get("teamId") == null ? null : Integer.valueOf(body.get("teamId").toString());
        Integer userId = body.get("userId") == null ? null : Integer.valueOf(body.get("userId").toString());
        String teamRole = body.get("teamRole") == null ? null : body.get("teamRole").toString();
        Integer operatorId = body.get("operatorId") == null ? null : Integer.valueOf(body.get("operatorId").toString());
    // 2) 与 GET 容错保持一致：无操作者ID则回退到被操作者ID
    if (operatorId == null && userId != null) {
            operatorId = userId;
        }
    // 3) 执行业务
    boolean success = teamService.updateMemberRole(teamId, userId, teamRole, operatorId);
        result.put("success", success);
        if (!success) {
            result.put("message", "更新失败，参数错误或权限不足");
        }
        return result;
    }

    // 获取成员角色：返回 { role }
    @RequestMapping(value = "/member/role/get", method = RequestMethod.GET)
    public Map<String, Object> getMemberRole(
            @RequestParam Integer teamId,
            @RequestParam Integer userId) {
        Map<String, Object> result = new HashMap<>();
    // 1) 查询成员记录并判断是否有效
    TeamMember member = teamService.getMember(teamId, userId);
        if (member != null && "active".equals(member.getStatus())) {
            result.put("success", true);
            Map<String, Object> data = new HashMap<>();
            data.put("teamId", teamId);
            data.put("userId", userId);
            data.put("teamRole", member.getTeamRole());
            result.put("data", data);
        } else {
            result.put("success", false);
            result.put("message", "成员不存在或已被移除");
        }
        return result;
    }

    // 兼容前端使用的REST风格路径：/team/{teamId}/member/{userId}/role
    @RequestMapping(value = "/{teamId}/member/{userId}/role", method = RequestMethod.GET)
    public Map<String, Object> getMemberRoleRest(@PathVariable Integer teamId, @PathVariable Integer userId) {
        Map<String, Object> result = new HashMap<>();
    // 1) 返回更简洁的 { role } 结构以适配前端
    TeamMember member = teamService.getMember(teamId, userId);
        if (member != null && "active".equals(member.getStatus())) {
            // 返回精简结构 { role: string } 以适配前端TeamRoleResp
            result.put("role", member.getTeamRole());
        } else {
            result.put("role", "member");
        }
        return result;
    }

    // 获取团队成员列表
    @RequestMapping(value = "/member/list", method = RequestMethod.GET)
    public Map<String, Object> getTeamMembers(@RequestParam Integer teamId) {
        Map<String, Object> result = new HashMap<>();
    // 1) 拉取成员列表用于团队详情页或管理页
        List<TeamMember> members = teamService.getTeamMembers(teamId);
        result.put("success", true);
        result.put("data", members);
        return result;
    }

    // 团队权限管理
    @RequestMapping(value = "/permission/add", method = RequestMethod.GET)
    public Map<String, Object> addPermission(
            @RequestParam Integer teamId,
            @RequestParam String resourceType,
            @RequestParam String action) {
        Map<String, Object> result = new HashMap<>();
    // 1) 新增默认权限，通常仅限团队管理员/leader
        boolean success = teamService.addPermission(teamId, resourceType, action);
        result.put("success", success);
        if (!success) {
            result.put("message", "添加权限失败");
        }
        return result;
    }

    // 更新团队权限
    @RequestMapping(value = "/permission/update", method = RequestMethod.GET)
    public Map<String, Object> updatePermission(
            @RequestParam Integer permissionId,
            @RequestParam String resourceType,
            @RequestParam String action) {
        Map<String, Object> result = new HashMap<>();
    // 1) 更新默认权限，服务层应校验记录存在性
        boolean success = teamService.updatePermission(permissionId, resourceType, action);
        result.put("success", success);
        if (!success) {
            result.put("message", "更新权限失败，权限可能不存在");
        }
        return result;
    }

    // 删除团队权限
    @RequestMapping(value = "/permission/delete", method = RequestMethod.GET)
    public Map<String, Object> deletePermission(@RequestParam Integer permissionId) {
        Map<String, Object> result = new HashMap<>();
    // 1) 删除默认权限
        boolean success = teamService.deletePermission(permissionId);
        result.put("success", success);
        if (!success) {
            result.put("message", "删除权限失败，权限可能不存在");
        }
        return result;
    }

    // 获取团队默认权限列表
    @RequestMapping(value = "/permission/list", method = RequestMethod.GET)
    public Map<String, Object> getTeamPermissions(@RequestParam Integer teamId) {
        Map<String, Object> result = new HashMap<>();
    // 1) 列出团队的默认权限配置，前端用于权限管理界面
        List<TeamDefaultPermission> permissions = teamService.getTeamPermissions(teamId);
        result.put("success", true);
        result.put("data", permissions);
        return result;
    }

    // 校验团队权限
    @RequestMapping(value = "/permission/check", method = RequestMethod.GET)
    public Map<String, Object> checkPermission(
            @RequestParam Integer teamId,
            @RequestParam Integer userId,
            @RequestParam String resourceType,
            @RequestParam String action) {
        Map<String, Object> result = new HashMap<>();
    // 1) 鉴权检查：用于前端按钮显隐或后端拦截前的显式检查
        boolean hasPermission = teamService.checkPermission(teamId, userId, resourceType, action);
        result.put("success", true);
        result.put("hasPermission", hasPermission);
        return result;
    }
}
